<?php

namespace App\Admin\Controllers;

use App\Exceptions\BizException;
use App\RiskRule;
use App\RiskRuleAli;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\MessageBag;

class RiskRuleAliController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '智租规则';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new RiskRuleAli());
        $grid->model()->orderByDesc('id');
        $grid->expandFilter();
        $grid->filter(function (Grid\Filter $filter) {

            $filter->disableIdFilter();

            $filter->column(1/2, function(Grid\Filter $filter){


                $filter->equal('zhfx', __('Zhfx'))->select(RiskRuleAli::getRuleName());
                $filter->equal('gzfx', __('Gzfx'))->select(RiskRuleAli::getRuleName());
                $filter->equal('yqfx', __('Yqfx'))->select(RiskRuleAli::getRuleName());


            });
            $filter->column(1/2, function(Grid\Filter $filter){
                $filter->equal('id', 'ID');
                $filter->equal('level', '等级')->select(RiskRuleAli::LEVEL_MAP);
            });
        });


        $grid->column('id', __('Id'));
        $grid->column('zhfx', __('Zhfx'))->using(RiskRuleAli::getRuleName())->label([1=>'success',2=>'success',3=>'warning',4=>'danger',5=>'danger']);
        $grid->column('gzfx', __('Gzfx'))->using(RiskRuleAli::getRuleName())->label([1=>'success',2=>'success',3=>'warning',4=>'danger',5=>'danger']);
        $grid->column('yqfx', __('Yqfx'))->using(RiskRuleAli::getRuleName())->label([1=>'success',2=>'success',3=>'warning',4=>'danger',5=>'danger']);
        $grid->column('level', __('Level'));
        $grid->column('status', '状态')->switch([
            'on'  => ['value' => 0, 'text' => '启用', 'color' => 'primary'],
            'off' => ['value' => 1, 'text' => '停用', 'color' => 'danger'],
        ]);
        $grid->column('dddd', '命中次数/占比')->display(function ($value) {
            $data = RiskRuleAli::getZhanbi($this->id);
            return $data['count'] .' | ' . $data['ratio'] . '%';
        });

        $grid->column('created_at', __('Created at'));
        $grid->column('updated_at', __('Updated at'));

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(RiskRuleAli::findOrFail($id));

        $show->field('id', __('Id'));
        $show->field('zhfx', __('Zhfx'));
        $show->field('gzfx', __('Gzfx'));
        $show->field('yqfx', __('Yqfx'));
        $show->field('status', __('Status'));
        $show->field('money', __('Money'));
        $show->field('age', __('Age'));
        $show->field('ultimately', __('Ultimately'));


        $show->field('created_at', __('Created at'));
        $show->field('updated_at', __('Updated at'));

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new RiskRuleAli());

        $form->saving(function (Form $form) {
            //保存前回掉

            //获取提交数据
            $data = \request()->input();


            try{

                if(!empty($data['money']) || !empty($data['age'])){
                    $result = RiskRule::conversionData($data);
                    if(!$result['status']){
                        throw new BizException($result['msg']);
                    }
                    foreach ($data as $key => $val){
                        if(!empty($val) && strpos($val,' ') !== false){
//                            throw new BizException('7777777777');
                            $form->$key = str_replace(" ","",$val);
                        }
                    }

                    //追加保存字段

                    $form->model()->ultimately = json_encode($result['arr']);

                    \Log::channel('push_pv')->info('规则列:',[$data,$result]);
                }


//                throw new BizException(json_encode($result['arr']));
            }catch (\Exception $e){

                $error = new MessageBag([
                    'title'   => '错误',
                    'message' => $e->getMessage(),
                ]);
                \Log::channel('push_pv')->info('智租规则保存失败:',[$data]);
                return back()->with(compact('error'));
            }

        });

        $form->saved(function (Form $form) {
            //保存后回掉
            Redis::del('rule_list_ali');
        });
        $form->text('money','金额限制')->default('')->help("金额限制在2000-4000只需填写:2000-4000 金额大于7000填:>,7000 其他符号有>,>=,==,-,<,");
        $form->text('age','年龄限制');
        $form->radio('zhfx', __('Zhfx'))->options(RiskRuleAli::getRuleName())->required();
        $form->radio('gzfx', __('Gzfx'))->options(RiskRuleAli::getRuleName())->required();
        $form->radio('yqfx', __('Yqfx'))->options(RiskRuleAli::getRuleName())->required();
        $form->radio('level', __('Dengji'))->options(RiskRuleAli::LEVEL_MAP)->required();
        $form->switch('status', '状态')->states([
            'on'  => ['value' => 0, 'text' => '启用', 'color' => 'primary'],
            'off' => ['value' => 1, 'text' => '停用', 'color' => 'danger'],
        ]);

        return $form;
    }
}
